package com.sky.controller.admin;


import cn.hutool.core.io.FileUtil;
import com.sky.result.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@RestController
@RequestMapping("/admin/common")
@Api(tags = "通用接口")
@Slf4j
public class CommonController {


    @Value("${riverlyn.file_upload_position}")
    public String file_upload_position;


    @PostMapping("/upload")
    @ApiOperation("文件上传")
    public Result<String> upload(MultipartFile file, HttpServletRequest request){
        String url=null;
        String fileFolderName= LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        if(!file.isEmpty()){
            try {
                String trueName=file.getOriginalFilename();
                String suffix=trueName.substring(trueName.lastIndexOf("."));
                String fileName= UUID.randomUUID()+suffix;

                //存储路径
                File dest=new File(file_upload_position+fileFolderName+"/"+fileName);
                //访问地址
                url= request.getScheme() + "://" +request.getServerName() + ":" + request.getServerPort() + "/admin/common/downloadFileByPath/" + fileFolderName + "/" +fileName;
                log.info("文件保存地址：{}",url);

                if (!dest.getParentFile().exists()){
                    dest.getParentFile().mkdirs();
                }

                file.transferTo(dest);
            }catch (Exception e){
                e.printStackTrace();
            }

        }
        return Result.success(url);
    }


    /**
     * 图片下载
     */
    @GetMapping("/downloadFileByPath/{fileFolderName}/{fileName}")
    @ApiOperation("文件下载")
    public ResponseEntity<Object> showImageByPath(@PathVariable(value = "fileFolderName") String fileFolder, @PathVariable(value = "fileName") String fileName){
        log.info("文件下载响应");
        StringBuilder path = new StringBuilder();
        path.append(fileFolder);
        path.append("/");
        path.append(fileName);
        //1,构造文件对象
        File file=new File(file_upload_position, String.valueOf(path));
        if(file.exists()) {
            //将下载的文件，封装byte[]
            byte[] bytes=null;
            try {
                bytes = FileUtil.readBytes(file);
            } catch (Exception e) {
                e.printStackTrace();
            }
            //创建封装响应头信息的对象
            HttpHeaders header=new HttpHeaders();
            //封装响应内容类型(APPLICATION_OCTET_STREAM 响应的内容不限定)
            header.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            //创建ResponseEntity对象
            ResponseEntity<Object> entity= new ResponseEntity<Object>(bytes, header, HttpStatus.CREATED);
            return entity;
        }
        return null;
    }

}
